package com.demo.controller;

import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.demo.domain.Notice;
import com.demo.model.R;
import com.demo.service.NoticeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;

@RestController
@RequestMapping("/notices")
public class NoticController {

        @Autowired
        private NoticeService noticeService;

        /**
         * 分页查询
         */
        @GetMapping
        public R<Page<Notice>> findByPage(Page<Notice> page, String title, String startTime, String endTime, Integer status) {
            page.addOrder(OrderItem.desc("last_update_time"));
            return R.ok(noticeService.findByPage(page, title, startTime, endTime, status));
        }


        @PostMapping("/delete")
        public R delete(@RequestBody String[] ids) {
            if (ids == null || ids.length == 0) {
                return R.fail("删除时需要给id的值");
            }
            boolean b = noticeService.removeByIds(Arrays.asList(ids));
            if (b) {
                return R.ok();
            }
            return R.fail("删除失败");
        }

        @PostMapping("/updateStatus")
        public R updateStatus(Long id,Integer status){
            Notice notice = new Notice();
            notice.setId(id);
            notice.setStatus(status);

            boolean b = noticeService.updateById(notice);
            if(b){
                return R.ok();
            }
            return R.fail();
        }

        @PostMapping
        public R add(@RequestBody Notice notice){
            notice.setStatus(1);
            boolean save = noticeService.save(notice);
            if(save){
                return R.ok();
            }
            return R.fail("新增公告失败");
        }

    @PatchMapping
    public R update(@RequestBody Notice notice){
        boolean update = noticeService.updateById(notice);
        if(update){
            return R.ok();
        }
        return R.fail("修改公告失败");
    }
}
